const express = require('express');
const router = express.Router();
const R = require("../util/json")
const connection = require("../util/db")
const json = require("../util/jsonFormat")

router.post("/update",function (req,res) {
    const {id,applyStartTime,applyEndTime,applyRemake,isCar,isDriver,carId}= req.body;
    if(id){
        let sql = "update apply set apply_remake = ?,apply_start_time = ?,apply_end_time = ?,is_car = ?,is_driver = ?,car_id = ? where id = ?";
        const objs = [applyRemake,applyStartTime,applyEndTime,isCar,isDriver,carId,id];
        connection.query(sql,objs,function (e) {
            if(e){
                throw e;
            }
            res.json(R.ok());
        })
    }else{
        let sql = "insert into apply(apply_id,apply_time,apply_remake,apply_start_time,apply_end_time,is_driver,is_car,car_id,status,apply_status,dep_exam_id,dep_exam_time,dep_exam_remake) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
        const objs = [req.loginId,new Date(),applyRemake,applyStartTime,applyEndTime,isDriver,isCar,carId?carId:null,1,req.roleId == 2 ? 2 : 1,req.roleId == 2?req.loginId:null,req.roleId == 2?new Date():null,req.roleId == 2?"同意":null];
        connection.query(sql,objs,function (e) {
            if(e){
                throw e
            }
            res.json(R.ok());
        })
    }
})

function extracted(apply, sql, objs) {
    if (apply.type == 1) {
        sql += "and apply_id = ? ";
        objs.push(apply.loginId);
    }
    if(apply.type == 2){
        if(apply.roleId == 2){
            sql+="and u2.department_id = ? ";
            objs.push(apply.departmentId)
        }
    }
    if(apply.type == 3){
        if(apply.roleId == 2){
            sql+="and u2.department_id = ? and a.apply_status = 1 ";
            objs.push(apply.departmentId)
        }else{
            sql+="and a.apply_status = 2 ";
        }
    }
    if(apply.type == 4){
        if(apply.roleId == 2){
            sql+="and u2.department_id = ? and a.apply_status = 2 ";
            objs.push(apply.departmentId)
        }else{
            sql+="and a.apply_status = 4 ";
        }
    }
    if (apply.timeRange) {
        const tr = apply.timeRange.split(",");
        const startTime = tr[0];
        const endTime = tr[1];
        sql += "and apply_start_time between ? and ? ";//只匹配开始时间范围
        objs.push(startTime, endTime);
    }
    if(apply.isDriver){
        sql+= "and a.is_driver = ? ";
        objs.push(apply.isDriver);
    }
    if(apply.applyStatus){
        sql +="and apply_status = ? ";
        objs.push(apply.applyStatus);
    }
    return sql;
}

router.get("/page",function (req, res) {
    const apply = req.query;
    apply.roleId=req.roleId;
    apply.loginId = req.loginId;
    apply.departmentId = req.loginInfo.departmentId;
    const {page=1,limit=5}=req.query;
    let objs = [];
    let sql = "select a.*,c.car_no,c2.car_no adminCarNo,u.nickname driverName,u2.nickname applyName from apply a left join car c on a.car_id = c.id left join car c2 on a.adm_car_id = c2.id left join userinfo u on a.adm_driver_id = u.id left join userinfo u2 on a.apply_id = u2.id where 1 = 1 ";
    sql = extracted(apply, sql, objs);
    sql+="order by apply_time desc limit ?,?";
    objs.push((page-1)*limit,parseInt(limit));
    connection.query(sql,objs,function (e,applyList,meta) {
        if(e){
            throw e
        }
        sql = "select count(a.id) count from apply a left join car c on a.car_id = c.id left join car c2 on a.adm_car_id = c2.id left join userinfo u on a.adm_driver_id = u.id left join userinfo u2 on a.apply_id = u2.id where 1 = 1 ";
        objs=[];
        sql = extracted(apply,sql,objs);
        connection.query(sql,objs,function (e,r) {
            if(e){
                throw e
            }
            res.json(R.page(r[0].count,json.formatArray(applyList,meta)));
        })
    })
})

router.get("/info/:id",function (req, res) {
    const id = req.params.id;
    connection.query("select * from apply where id = ?",[id],function (e,r,meta) {
        if(e){
            throw e;
        }
        if(r.length === 1){
            const apply = json.formatObject(r[0],meta);
            if(apply.applyId != req.loginId || (req.roleId == 2 && apply.applyStatus != 2) || (req.roleId == 3 && apply.applyStatus != 1)){
                res.json(R.error("编号异常！"));
            }else{
                res.json(R.data(apply))
            }
        }else{
            res.json(R.error("编号异常！"))
        }
    })
})

router.get("/detail/:id",function (req,res) {
    const id = req.params.id;
    connection.query("select a.*,c.car_no,c2.car_no adminCarNo,u.nickname driverName,u2.nickname applyName,u3.nickname depExamName,u4.nickname admExamName from apply a left join car c on a.car_id = c.id left join car c2 on a.adm_car_id = c2.id left join userinfo u on a.adm_driver_id = u.id left join userinfo u2 on a.apply_id = u2.id left join userinfo u3 on a.dep_exam_id = u3.id left join userinfo u4 on a.adm_exam_id = u4.id where a.id = ?",[id],function (e,r,meta) {
        if(e){
            throw e
        }
        if(r.length === 1){
            res.json(R.data(json.formatObject(r[0],meta)));
        }else{
            res.json(R.error("编号异常"));
        }
    })
})
router.post("/exam",function (req, res) {
    const { id, status, driverId, carId,remake } = req.body;
    const loginId = req.loginId;
    const roleId = req.roleId;
    if(roleId == 2){
        /*status1表示同意2表示拒绝需要转为负责人同意的2和负责人拒绝的3*/
        let sql = "update apply set dep_exam_id = ?,dep_exam_time = ?,dep_exam_remake = ?,apply_status = ? where id = ?";
        const objs=[loginId,new Date(),remake,status == 1 ? 2 :3,id];
        connection.query(sql,objs,function (e) {
            if(e){
                throw e;
            }
            res.json(R.ok());
        })
    }
    if(roleId == 1){
        let sql = "update apply set adm_exam_id = ?,adm_exam_time = ?,adm_exam_remake = ?,apply_status = ?,adm_driver_id = ?,adm_car_id = ? where id = ?";
        const objs=[loginId,new Date(),remake,status == 1 ? 4 : 5,status == 1 ? driverId:null,status == 1 ?carId:null,id];
        connection.query(sql,objs,function (e){
            if(e){
                throw e;
            }
            res.json(R.ok());
        })
    }
})

router.delete("/delete/:id",function (req, res) {
    const roleId = req.roleId;
    const id = req.params.id;
    if(roleId == 1){
        connection.query("select * from apply where id = ?",[id],function (e,r) {
            if(e){
                throw e;
            }
            if(r.length===1){
                const apply = json.formatObject(r[0]);
                if(apply.applyStatus == 6 || apply.applyStatus == 7){
                    connection.query("delete from apply where id = ?",[id],function (e) {
                        if(e){
                            throw e;
                        }
                        res.json(R.ok());
                    })
                }else{
                    res.json(R.error("无权删除该订单！"))
                }
            }else{
                res.json(R.error("编号异常，无法删除！"))
            }
        })
    }else{
        res.json(R.error("无权删除该订单！"))
    }
})
router.post("/return/car",function (req, res) {
    const id = req.body.id;
    const loginId = req.loginId;
    connection.query("select * from apply where id = ?",[id],function (e,r) {
        if(e){
            throw e;
        }
        if(r.length === 1){
            const apply = json.formatObject(r[0]);
            if(apply.applyId == loginId){
                if(apply.applyStatus == 4){
                    connection.query("update apply set apply_status = 6,return_time = ? where id = ?",[new Date(),id],function (e) {
                        if(e){
                            throw e;
                        }
                        res.json(R.ok());
                    })
                }else{
                    res.json(R.error("订单异常无法还车"))
                }
            }else{
                res.json(R.error("非申请人无法还车!"))
            }
        }else{
            res.json(R.error("编号异常!"))
        }
    })
})
module.exports = router;
